# 自研的表格识别应用层
import numpy as np
from common.get_hw_pre import getresult
import json

from tree_editdist import tree_distance

filenames = []
anns = []
num_label = 0
num_chars = 0

for line in open("table/Label.txt", "r", encoding='utf-8'):
    strs = line.split("\t")
    filename = strs[0]
    filenames.append(filename)
    anns.append(json.loads(strs[1]))
sample_metrics = []
all_pre_cell_infos = []
class_labels = []
for k in range(0, 10):
    i = 6
    # 第i个文件
    label = anns[i]
    # 文本行检测
    label_chars = []
    labe_char_boxes = []

    class_label = []
    class_pre = []
    class_pre_boxs = []
    class_label_boxs = []
    cell_label_boxs = []
    cell_rowcols = []

    tables_boxs = []
    #label
    for j in range(len(label)):
        value = label[j]["transcription"]
        if value == 'picture':
            class_label.append(0)
            xyxy = label[j]["points"][0] + label[j]["points"][2]
            class_label_boxs.append(xyxy)
        elif value == 'paragraph':
            class_label.append(1)
            xyxy = label[j]["points"][0] + label[j]["points"][2]
            class_label_boxs.append(xyxy)

        elif value == 'table':
            class_label.append(2)
            xyxy = label[j]["points"][0] + label[j]["points"][2]
            class_label_boxs.append(xyxy)

        elif value.split("-")[0] == 'cell':
            class_label.append(3)
            xyxy = label[j]["points"][0] + label[j]["points"][2]
            class_label_boxs.append(xyxy)
            cell_label_boxs.append(xyxy)
            strs = value.split("-")
            row_cols = [int(strs[1]), int(strs[2]), int(strs[3]), int(strs[4])]
            cell_rowcols.append(row_cols)
        else:
            label_chars.append(value)
            xyxy = label[j]["points"][0] + label[j]["points"][2]
            labe_char_boxes.append(xyxy)
    # 所有表格的box
    tables_boxs = np.array(class_label_boxs)[class_label == np.array(2)]
    #tabels_infos: [table1,table2]
    # table1:[ cell1 ,cell2 ]
    # cell:[[x y x y][linechar1,linechar2]]
    tabels_infos = []
    # 对每一个表格，寻找内部的所有cell
    for table_box in tables_boxs:
        #哪些cell 在表格中
        label_cells_info = []
        for index_cell, cell_box in enumerate(cell_label_boxs):
            if cell_box[0] >= table_box[0] and cell_box[1] >= table_box[1] and cell_box[2] <= table_box[2] and cell_box[3] <= table_box[3]:
                # label_current_table_cells.append(cell_box)
                chars = []
                # cell 里面有哪些字符串行
                for index_char, char_box in enumerate(labe_char_boxes):
                    if char_box[0] >= cell_box[0] and char_box[1] >= cell_box[1] and char_box[2] <= cell_box[2] and \
                            char_box[3] <= cell_box[3]:
                        chars.append(label_chars[index_char])
                if len(chars) == 0:
                    chars = [""]
                label_cells_info.append([cell_rowcols[index_cell], chars])
        tabels_infos.append(label_cells_info)


    # pre:
    pre_chars = []
    pre_boxes = []
    pre_table_infos = []
    pre = getresult(filenames[i])
    if 'Picture' in pre.keys():
        for class_info in pre["Picture"]:
            coords = class_info["coords"]
            class_pre_boxs.append([coords[0], coords[1], coords[4], coords[5]])
            class_pre.append(0)
    if 'Paraph' in pre.keys():
        for class_info in pre["Paraph"]:
            coords = class_info["coords"]
            class_pre_boxs.append([coords[0], coords[1], coords[4], coords[5]])
            class_pre.append(1)

    if 'Table' in pre.keys():
        for class_info in pre["Table"]:
            pre_cell_info = []
            coords = class_info["coords"]
            class_pre_boxs.append([coords[0], coords[1], coords[4], coords[5]])
            class_pre.append(2)
            for cell in class_info["cell"]:
                class_pre.append(3)
                coords = cell["coords"]
                class_pre_boxs.append([coords[0], coords[1], coords[4], coords[5]])
                all_pre_lines_chars = []
                for para in cell['paragh']:
                    lines = para["line"]
                    # all_pre_lines_chars = all_pre_lines_chars + lines
                    for line in lines:
                        all_pre_lines_chars.append(line["code"])
                if len(all_pre_lines_chars) == 0:
                    all_pre_lines_chars = [""]
                pre_cell_info.append([[cell['row'][0], cell['row'][1], cell['col'][0], cell['col'][1]], all_pre_lines_chars])
            pre_table_infos.append(pre_cell_info)
    from common.detect import get_per_img_statistics_tab
    metrics, table_index= get_per_img_statistics_tab(class_pre_boxs, class_label_boxs, 0.5, class_pre, class_label)
    # for class_result in metrics:
    #     # 去掉预测结果中多余的table
    #     if class_result[2][0] == 2:
    #         pre_table_infos = np.array(pre_table_infos)[class_result[0] == np.array(1)]
    #         pre_table_infos = list(pre_table_infos)
        ###### 删除tp = 0 的 cell
        # if class_result[2][0] == 3:
        #     cell_len_pre_table = []
        #     for jj in range (len(pre_table_infos)) :
        #         cell_len_pre_table.append(len(pre_table_infos[jj]))
        #     cell_len_pre_table = np.array(cell_len_pre_table).cumsum()
        #     box_del_indexs = list(np.where(class_result[0] == np.array(1)))[0]
        #     if len(box_del_indexs) != 0:
        #         for index in box_del_indexs:
        #             for kkk in range(len(cell_len_pre_table)):
        #                 if index < cell_len_pre_table[kkk]:
        #                     temp = 0
        #                     if not kkk - 1 < 0:
        #                         temp = cell_len_pre_table[kkk-1]
        #                     true_index = index - temp
        #                     pre_table_infos[kkk] = np.delete(pre_table_infos[kkk], true_index)
        #                     # del pre_table_infos[kkk][true_index]
        #                     break
    sample_metrics += metrics
    # all_pre_cell_infos += cellinfos
    for index_ in range(len(tabels_infos)):
        aaa = tree_distance(pre_table_infos[index_], tabels_infos[table_index[index_]])
    class_labels += class_label
true_positives, pred_scores, recong_dist, recong_dist_no_del = [np.concatenate(x, 0) for x in list(zip(*sample_metrics))]
pass